package org.linlinjava.litemall.admin.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.ocean.rawsdk.ApiExecutor;
import com.alibaba.ocean.rawsdk.common.SDKResult;
import com.alibaba.product.param.AlibabaCpsMediaProductInfoResult;
import com.alibaba.product.param.AlibabaProductFollowParam;
import com.alibaba.product.param.AlibabaProductFollowResult;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.linlinjava.litemall.admin.alibaba.AlibabaCpsMediaProductInfoParam;
import org.linlinjava.litemall.admin.alibaba.AlibabaCpsOpListCybUserGroupFeedParam;
import org.linlinjava.litemall.admin.alibaba.AlibabaCpsOpListCybUserGroupParam;
import org.linlinjava.litemall.admin.alibaba.AlibabaCpsOpListCybUserGroupResult;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.admin.service.AdminGoodsService;
import org.linlinjava.litemall.admin.service.AlibabaService;
import org.linlinjava.litemall.admin.vo.ProductsVo;
import org.linlinjava.litemall.core.config.GlobalConfig;
import org.linlinjava.litemall.admin.service.AlibabaGoodsChangeService;

import org.linlinjava.litemall.core.util.ResponseUtil;

import org.linlinjava.litemall.db.domain.ProductLibrrary;
import org.linlinjava.litemall.db.domain.Products;
import org.linlinjava.litemall.db.service.LitemallAdService;
import org.linlinjava.litemall.db.service.ProductLibriaryService;
import org.linlinjava.litemall.db.service.ProductsService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/admin/alibaba")
@Validated
public class AdminAlibabaController {
    private final Log logger = LogFactory.getLog(AdminAlibabaController.class);

    @Autowired
    private LitemallAdService adService;
    @Autowired
    private AlibabaGoodsChangeService alibabaGoodsChangeService;
    @Autowired
    private AlibabaService alibabaService;
    @Autowired
    private ProductsService productsService;
    @Autowired
    private ProductLibriaryService productLibriaryService;
    @Autowired
    private AdminGoodsService adminGoodsService;
    //@Autowired
   // private ApiExecutor apiExecutor;


    /**
     * 根据id删除products表
     * 此处是真实删除非逻辑删除
     * */
    @RequiresPermissions("admin:alibaba:delete")//检测是否有执行此方法的权限
    @RequiresPermissionsDesc(menu = {"库存同步", "删除products"}, button = "删除")
    @GetMapping("/deleteProduct")
    public Object deleteProduct(Integer id){
        productsService.delete(id);
        return ResponseUtil.ok();
    }
    /**
     * 批量同步
     * */
    @RequiresPermissions("admin:alibaba:batchSncyProducts")//检测是否有执行此方法的权限
    @RequiresPermissionsDesc(menu = {"库存同步", "批量同步"}, button = "批量同步商品到goods表")
    @PostMapping("/batchSncyProducts")
    public Object batchSncyProducts(String productslist,Long categoryId,Float franking,Boolean selfPrice){

            String[]  arr = productslist.split(",");
            for (String temp:arr){
                alibabaService.getProductInfo(Long.valueOf(temp), franking, selfPrice,categoryId);
            }
            return ResponseUtil.ok();
    }

    /**
     * 查询类库下的所有商品
     * */
    @RequiresPermissions("admin:alibaba:getListByGroupId")//检测是否有执行此方法的权限
    @RequiresPermissionsDesc(menu = {"库存同步", "获取类库商品列表(系统内部)"}, button = "获取productId")
    @GetMapping("/getListByGroupId")
    public Object getListByGroupId(Long libraryid,Integer status,Integer pageNo,Integer size){
        if(libraryid==null||libraryid.equals(null)||libraryid<0)
            libraryid = 3571L;
        List<Products> productsList = alibabaGoodsChangeService.productListByLibraryId(libraryid,status,pageNo,size);
        List<ProductLibrrary> libarylist = alibabaGoodsChangeService.productLibrarylist();
         Object obj =adminGoodsService.list2();
        Integer totalRow  = alibabaGoodsChangeService.getNumTotal(libraryid, status);
        Map<String ,Object> map = new HashedMap();
        map.put("productList", productsList);
        map.put("libraryList", libarylist);
        map.put("totalRow", totalRow);
        map.put("cateGoryList", obj);

        return ResponseUtil.ok(map);
    }


    /**
     * 根据groupId同步商品
     * */
    @RequiresPermissions("admin:alibaba:listCybUserGroupFeed")//检测是否有执行此方法的权限
    @RequiresPermissionsDesc(menu = {"库存同步", "同步类库商品"}, button = "获取products")
    @GetMapping("/listCybUserGroupFeed")
    public Object listCybUserGroupFeed(Long libraryid) {
            Integer pageNo=1;

            Integer pageSize=10;
        if(libraryid==null||libraryid<=0)
           // return ResponseUtil.badArgument();
            libraryid = 3715L;//如果未传入就设置默认的选品库  3715

       Object obj=alibabaService.listCybUserGroupFeed(libraryid, pageNo, pageSize);


        JSONObject  jsonObj = JSONObject.parseObject(obj.toString());
        jsonObj  = JSONObject.parseObject(jsonObj.get("result").toString());

        //logger.info("log");
        if(Integer.parseInt(jsonObj.get("totalRow").toString())>0) {
            this.Obj2Products(jsonObj.get("resultList"), libraryid);
            int j = Integer.parseInt(jsonObj.get("totalRow").toString()) / pageSize + 1;

            for (int i = 2; i <= j; i++) {
                Object objlist = alibabaService.listCybUserGroupFeed(libraryid, i, pageSize);


                JSONObject jsonObjlist = JSONObject.parseObject(objlist.toString());
                jsonObjlist = JSONObject.parseObject(jsonObjlist.get("result").toString());
                if (Integer.parseInt(jsonObjlist.get("totalRow").toString()) > 0)
                    this.Obj2Products(jsonObjlist.get("resultList"), libraryid);
            }

        }
        return ResponseUtil.ok(obj);
    }
    public   void  Obj2Products(Object obj,Long groupId){

        JSONArray arr = JSON.parseArray(obj.toString());
        for (int i = 0 ;i<arr.size();i++){
            JSONObject jsonli = JSONObject.parseObject(arr.get(i).toString());
           Products products = new Products();

           products.setFeedId(jsonli.get("feedId").toString());
           products.setLibraryId(groupId.intValue());
            if(jsonli.get("imgUrl")!=null)
                products.setImgurl(jsonli.get("imgUrl").toString());
           if(jsonli.get("saleCount")!=null)
                 products.setSalecount(jsonli.get("saleCount").toString());
           if(jsonli.get("price")!=null)
                products.setPrice(jsonli.get("price").toString());
            if(jsonli.get("title")!=null)
                products.setTitle(jsonli.get("title").toString());
            if(jsonli.get("promotionPrice")!=null)
                products.setPromotionPrice(jsonli.get("promotionPrice").toString());
            if(jsonli.get("promotionSpace")!=null)
                products.setPromotionSpace(jsonli.get("promotionSpace").toString());

            if(jsonli.get("invalidInfo")!=null)
                products.setInvalidinfo(jsonli.get("invalidInfo").toString());
            if(jsonli.get("invalid")!=null){
                products.setInvalid(Boolean.getBoolean(jsonli.get("invalid").toString())?0:1);
            }else {
                products.setInvalid(1);
            }

           products.setStatus(0);
           productsService.validAndAdd(products);
        }
    }
    /**
     * 获取选品库列表
     * */
    @RequiresPermissions("admin:alibaba:listCybUserGroup")//检测是否有执行此方法的权限
    @RequiresPermissionsDesc(menu = {"库存同步", "同步选品库"}, button = "获取选品库")
    @GetMapping("/listCybUserGroup")
    public Object listCybUserGroup() {
        int pageSize =10;
        logger.info("开始同步选品库");
        SDKResult<AlibabaCpsOpListCybUserGroupResult> result =alibabaService.listCybUserGroup("1", String.valueOf(pageSize));
        if(result.getResult()!=null&&result.getResult().getResult()!=null){
            this.Obj2ProductLibrary(result.getResult().getResult());
            int j = Integer.parseInt(JSONObject.parseObject(result.getResult().getResult().toString()).get("totalRow").toString())/pageSize +1;
            for(int i=2;i<=j;i++){
                SDKResult<AlibabaCpsOpListCybUserGroupResult> obj=alibabaService.listCybUserGroup(String.valueOf(i), String.valueOf(pageSize));
                this.Obj2ProductLibrary(obj.getResult().getResult());
            }
        }

        return ResponseUtil.ok();
    }

    public   void  Obj2ProductLibrary(Object obj){

        JSONArray arr = JSON.parseArray(JSONObject.parseObject(obj.toString()).get("result").toString());
        for (int i = 0 ;i<arr.size();i++){
            JSONObject jsonli = JSONObject.parseObject(arr.get(i).toString());
            ProductLibrrary products = new ProductLibrrary();
            products.setFeedCount(Integer.valueOf(jsonli.get("feedCount").toString()));
            products.setProductLibraryId(Integer.valueOf(jsonli.get("id").toString()));
            products.setTitle(jsonli.get("title").toString());
            products.setCreateTime(LocalDateTime.now());
            productLibriaryService.validAndAdd(products);
        }
    }
    /**g根据商品ProdectId获取商品信息*/
    @RequiresPermissions("admin:alibaba:productInfo")//检测是否有执行此方法的权限
    @RequiresPermissionsDesc(menu = {"库存同步", "单个商品同步"}, button = "获取商品详情")
    @GetMapping("/productInfo")
    public Object productInfo(Long offerId,Float franking,Boolean selfPrice) {
        int flag =0;

        if(offerId==null||offerId<0){

            return ResponseUtil.fail();
        }

        if(alibabaService.productFollow(offerId)){
            flag = alibabaService.getProductInfo(offerId,franking,selfPrice,Long.valueOf(0));

        }else {
          //  return new ResponseEntity<>(new ReturnValue(ReturnValue.fail, "建立商品关系失败"), HttpStatus.OK);
            return ResponseUtil.ok( "建立商品关系失败");
        }

        //return new ResponseEntity<>(new ReturnValue(ReturnValue.success, alibabaGoodsChangeService.getMessage()), HttpStatus.OK);
        return ResponseUtil.ok(alibabaGoodsChangeService.getMessage());
    }

    /**g根据商品ProdectId
     * categoryiD同步商品信息
     * */
    @RequiresPermissions("admin:alibaba:productInfoByCateGoryId")//检测是否有执行此方法的权限
    @RequiresPermissionsDesc(menu = {"库存同步", "同步商品到指定分类"}, button = "同步商品")
    @GetMapping("/productInfoByCateGoryId")
    public Object productInfoByCateGoryId(Long offerId,Long categoryId) {
        int flag =0;

        if(offerId==null||offerId<0){

            return ResponseUtil.fail();
        }
        if(categoryId==null||categoryId<0){
            return  ResponseUtil.ok("分类id不可为空");
        }
        if(alibabaService.productFollow(offerId)){
            flag = alibabaService.getProductInfo(offerId,0f,false,categoryId);

        }else {
            //  return new ResponseEntity<>(new ReturnValue(ReturnValue.fail, "建立商品关系失败"), HttpStatus.OK);
            return ResponseUtil.ok( "关注商品失败");
        }

        //return new ResponseEntity<>(new ReturnValue(ReturnValue.success, alibabaGoodsChangeService.getMessage()), HttpStatus.OK);
        return ResponseUtil.ok(alibabaGoodsChangeService.getMessage());
    }



    private ApiExecutor  apiExecutor(){
        //获取配置信息appid和appsecret
        ApiExecutor apiExecutor = new ApiExecutor(GlobalConfig.AlibabaAppId,GlobalConfig.AlibabaAppSecret);
        return apiExecutor;
    }







}
